﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Forum.Common.Messages;

namespace client
{
    class Client
    {
        private ClientMessageHandler msgHandler;

        public Client()
        {
            this.msgHandler = null;
        }

        public void initClient()
        {
            try
            {
             //   Console.WriteLine("before connection  -client");  ///
                TcpClient client = new TcpClient("localhost", 8000); // have my connection established with a Tcp Server
                //  TcpClient client = new TcpClient("127.0.0.1", 8000);
              //  Console.WriteLine("after connection -client");  ///
                
                IFormatter formatter = new BinaryFormatter(); // the formatter that will serialize my object on my stream 

                this.msgHandler = new ClientMessageHandler(client);

                

                Message msg;
                NetworkStream strm;
                int _countMsg = 0;  ///
                while (true)
                {
                   
                    strm = client.GetStream();
                    msg = (Message)formatter.Deserialize(strm);

                    //if (msg.GetType().Equals("ReisterResult")){
                   // Logger.log(String.Format("<IP:{0}> SEND DATA: {1}", ((IPEndPoint)client.Client.RemoteEndPoint).Address, ((RegisterResult)msg).succ));}
                    //Console.WriteLine("send from server to client number {0} - {1}", _countMsg,msg.GetType());  ///
                    this.msgHandler.proccessMsg(msg, strm);
                    _countMsg++;  ///
                }

                Console.ReadLine();

                strm.Close();
                client.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        static void Main(string[] args)
        {

            Client c = new Client();
            c.initClient();


            Console.ReadLine();

        }

    }
}
